package com.foogui.utils;

import com.foogui.config.JedisFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Jedis;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class JedisLock implements ILock {

    public static final String UUID = cn.hutool.core.lang.UUID.randomUUID().toString(true) + "-";

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";

    @Autowired
    private JedisFactory jedisFactory;

    /**
     * 占用锁
     *
     * @param lockName 锁key
     * @return 锁id
     */
    @Override
    public boolean tryLock(String lockName, Long timeout, TimeUnit timeUnit) {
        //获得jedis实例
        Jedis jedis = jedisFactory.getJedis();
        //锁id（必须拥有此id才能释放锁）
        String value = UUID + Thread.currentThread().getId();
        //占用锁同时设置失效时间

        String isLock = jedis.set(lockName, value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, 15000);
        //占用锁成功返回锁id，否则返回null
        if (LOCK_SUCCESS.equals(isLock)) {
            return true;
        }
        return false;
    }

    @Override
    public void unlock(String lockName) {

    }
}
